<?php
namespace app\admin\model;

use app\index\model\Cate;
use think\Model;

class News extends Model{

    private $newsModel;
    public function __construct(){
        parent::__construct();
        $this -> newsModel = db('news');
    }

    public function getNewsList($where,$order = false , $num = 10 , &$page , $type = 1){
        $newsData = $this -> newsModel -> where($where) -> order($order) -> paginate($num,false,['query'=>request()->param() ]);
        $page = $newsData->render();
        $data = iterator_to_array($newsData);
        if(empty($data)){   return [];  }
        //格式化数据
        switch ($type) {
            case 1:
                $dataList = $this -> formatNewsDataList($data);
                break;

            default:
                # code...
                break;
        }
        return $dataList;
    }

    /*  格式化资讯列表
     *
     * **/
    public function formatNewsDataList($data){
        $type = config('newstype');
        $cateModel = new Cate();
//        getCateValue
        foreach ($data as $key => $value) {
            $list[$key]['id'] = $value['id'];
            $list[$key]['author'] = $value['author'];
            $list[$key]['img'] = $value['img'];
            $list[$key]['cname'] = $cateModel -> getCateValue(['id'=>$value['cate_id']],'name');
            $list[$key]['title'] = $value['title'];
            $list[$key]['sign'] = formatNewsDetailForSign($value['detail'],20);
            $list[$key]['read_num'] = $value['read_num'];
            $list[$key]['order'] = $value['order'];
            $list[$key]['reco_index'] = $value['reco_index'];
            $list[$key]['type'] = $type[$value['type']];
            $list[$key]['addtime'] = date("Y-m-d H:i:s",$value['addtime']);
        }
        return $list;
    }

    /*  资讯详情
     *
     * **/
    public function getNewsDetail($where){
        $data = $this -> newsModel -> where($where) -> find();
        if(empty($data)){   return [];  }
        //格式化数据
        $info = $this -> formatNewsDetail($data);
        return $info;
    }

    /* 格式化详情数据  */
    public function formatNewsDetail($data){
        $data['image'] = explode(',',$data['image']);
        $data['addtime'] = date('Y-m-d H:i:s',$data['addtime']);
        return $data;
    }


    /*  发布资讯
     *
     * **/
    public function addNews($data){
        $result = $this -> newsModel -> insertGetId($data);
        return $result;
    }

    /*  修改信息
    *  @param field [field]
    *  @return res
    * **/
    public function modify($where = false , $save = false ){
        $result = $this -> newsModel -> where($where) -> update($save);
        return $result;
    }


}